/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package user;

import commun.DBManager;
import commun.Message;
import java.sql.PreparedStatement;
import java.util.ArrayList;



/**
 *
 * @author Qiao Bingzhi
 */
public class UserManager implements _UserManager{
    
   //Generator  of user id
    
   public String newId() {
        DBManager db=new DBManager();
        String id= null;
        try
        {
          String sql="select count(*) from Users";
          String maxId = db.getResult(sql).toString();
          db.close();
          id = String.valueOf(Integer.parseInt(maxId)+1);
        }
        catch(Exception e)
        {
         e.printStackTrace();
        }
        return id;
    }
   
   
    public String newUser(User user,String pwd) {
        String sql = "insert into Users values(?,?,?,?,?,?,?)";
        String id =newId();
	DBManager db = new DBManager();
	PreparedStatement pstat = db.getPreparedStat(sql);
        try
        {
          pstat.setString(1,id);
          pstat.setString(2,pwd);
          pstat.setString(3,user.getUserName());
          pstat.setString(4,user.getSex());
          pstat.setString(5,user.getEmail());
          pstat.setString(6,user.getBirthDay());
          pstat.setString(7,user.getTelNumber());
          pstat.execute();       
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
        db.close();
        return id;
    }

    public User getUserById(String id) {
        User tmp=new User();
        DBManager db=new DBManager();
        String sql="select * from Users where IdUser='"
                   + id + "'";
        String[][] rslt=db.getResults(sql);
          
            if(rslt!=null)
            {    
            tmp.setUserId(id);
            tmp.setUserName(rslt[0][2]);
            tmp.setSex(rslt[0][3]);
            tmp.setEmail(rslt[0][4]);
            tmp.setBirthDay(rslt[0][5]);
            tmp.setTelNumber(rslt[0][6]);                 
            }
            db.close();
        
       return tmp;  
        
    }

    public User[] getAllUsers() {
        ArrayList list = new ArrayList();
	DBManager db = new DBManager();
	String sql = "select IdUser,UserName,Sex,Email,birthDay,TelNumber from Users";
	String[][] rslt = db.getResults(sql);
	if(rslt==null) return null;
	int count=rslt.length;
	for(int i=0;i<count;i++){
	   User tmp=new User();
           tmp.setUserId(rslt[i][0]);
           tmp.setUserName(rslt[i][1]);
           tmp.setSex(rslt[i][2]);
           tmp.setEmail(rslt[i][3]);
           tmp.setBirthDay(rslt[i][4]);
           tmp.setTelNumber(rslt[i][5]);
	   list.add(tmp);
	}
	db.close();
	User[]users=new User[list.size()];
	for(int i=0;i<users.length;i++){
	users[i]=(User)list.get(i);
	}
	return users;
    }

    public boolean checkLogin(Login login) {
          boolean rslt=false;
          DBManager db=new DBManager();
          String sql="select UserName from Users where IdUser='"+login.getUserId()+"'"+" and Pwd='"
                     +login.getPassword()+"'";
          String userName =(String)db.getResult(sql);
          System.out.println(userName);
          if(userName!=null && !userName.equals(""))
              rslt=true;
          db.close();
          return rslt;
    }

    public String getIdByUserName(String userName) {
        DBManager db=new DBManager();
          String sql="select IdUser from Users where UserName='" + userName +"'";
          String id=(String)db.getResult(sql);
          return id;
    }

    public boolean addFriend(String id1, String id2) {
        boolean result = false;
	DBManager db = new DBManager();
  String sql = "select count(*) from Users where IdUser='" + id1 + "' or IdUser='"
				+ id2 + "'";
		int count = ((Integer) db.getResult(sql)).intValue();
	//	System.out.println(count);
		if (count == 2) {
			try {
				
				sql = "delete from Friends where IdHost='" + id1 + "' and IdFriend='"
						+ id2 + "'";
				db.update(sql);
				sql = "delete from Friends where IdHost='" + id1 + "' and IdFriend='"
						+ id2 + "'";
				db.update(sql);
				sql = "insert into Friends values('''," + id1 + "','" + id2
						+ "')";
				db.update(sql);
				sql = "insert into Friends values('''," + id1 + "','" + id2
						+ "')";
				db.update(sql);
				
				result = true;
				db.close();
			} catch (Exception exx) {
				exx.printStackTrace();
			}
		}
		return result;
    }

    public boolean MessageSaver(Message message) {
        boolean flag=false;
        DBManager db=new DBManager();
	String sql="insert into Messages (FromId,ToId,Message,Date) values (?,?,?,?)";
			PreparedStatement ps=db.getPreparedStat(sql);
			if(ps!=null){
				try {
					ps.setString(1,message.getFromId());
					ps.setString(2,message.getToId());
					ps.setString(3,message.getMessage());
					ps.setString(4, message.getDate());
					ps.execute();
					ps.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                                
			flag=true;
			}
                        db.close();
			
		
           return flag;
		
    }

    public ArrayList MessageGetter(String id) {
        ArrayList list=new ArrayList();
		DBManager db = new DBManager();
		String sql = "select FromId,ToId,Message,Date from Messages where  ToId='"+id+"' order by Date";
		String[][] rslt = db.getResults(sql);
		if(rslt==null) return null;
		int count=rslt.length;
		for(int i=0;i<count;i++){
			Message message =new Message(rslt[i][0],rslt[i][1],rslt[i][2],rslt[i][3]);
			
			list.add(message);
		}
                //delet the message
		//sql="update message set isread=true where to='"+id+"'";
		//db.update(sql);
		db.close();
		return list;
    }

    public User[] getAllFriends(String id) {
        User[] users = new User[0];
	ArrayList tmp = new ArrayList();
	DBManager db = new DBManager();
	String sql = "select IdUser,UserName,Sex,Email,birthDay,TelNumber from Users u,Friends f where u.IdUser=f.IdFriend and f.Idhost='"
			+ id + "'";
	String[][] rows = db.getResults(sql);
	if (rows != null) {
		for (int i = 0; i < rows.length; i++) {
			User user = new User();
                        user.setUserId(rows[i][0]);
                        user.setUserName(rows[i][1]);
                        user.setSex(rows[i][2]);
                        user.setEmail(rows[i][3]);
                        user.setBirthDay(rows[i][4]);
                        user.setTelNumber(rows[i][5]);
                        tmp.add(user);
            }
			if (!tmp.isEmpty()) {
				int size = tmp.size();
				users = new User[size];
				for (int j = 0; j < size; j++) {
					users[j] = (User) tmp.get(j);
				}
			}
        }
  
		return users;
        
 
    }

    
 public static void main(String args[])
 {
         UserManager user=new UserManager();
         
         User tmp =new User();
         /*
         tmp.setUserName("damien");
         tmp.setSex("homme");
         tmp.setEmail("damien@gmail.com");
         tmp.setBirthDay("1983/04/3");
         tmp.setTelNumber("12345642");
         System.out.println("The id of the user is :");
         String id=user.newUser(tmp, "123");
          */
         System.out.println(user.checkLogin(new Login("6","123456")));
        // System.out.println(id);
        
         
         
 
 
 }    
    

}
